﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ObjectModel;
using System.Reflection;

namespace SAIPS.Controllers
{
    public class BaseController<T> : Controller where T:BaseEntity<T>
    {
		public virtual ActionResult Index()
		{
			return View(createInstance().select("where removed=0").ToList());
		}

		public virtual ActionResult Edit(int? id)
		{
			return View(createInstance().select("where id=" + id).FirstOrDefault());
		}

		public virtual ActionResult Delete(int? id)
		{
			return View(createInstance().select("where id=" + id).FirstOrDefault());
		}

		public virtual ActionResult Remove(FormCollection form)
		{
			var obj = fillObj(form);
			if (obj == null)
				return RedirectToAction("Index");
			obj.delete();
			return RedirectToAction("Index");
		}

		public virtual ActionResult Create()
		{
			return View(createInstance());
		}

		public virtual ActionResult Insert(FormCollection form)
		{
			var obj = fillObj(form);
			//TODO: address
			obj.insert();
			return RedirectToAction("Index");
		}

		public virtual ActionResult Update(FormCollection form)
		{
			var obj = fillObj(form);
			obj.Id = Convert.ToInt32(form["Id"]);
			//TODO: address
			obj.update();
			return RedirectToAction("Index");
		}

		BaseEntity<T> fillObj(FormCollection form)
		{
			if (form == null || form.AllKeys.Length == 0 || form.Count == 0)
				return null;
			var ass = Assembly.GetExecutingAssembly();
			var obj = createInstance();
			foreach (var p in obj.GetType().GetProperties())
			{
				if (String.IsNullOrEmpty(form[p.Name]))
					continue;
				p.SetValue(obj, Convert.ChangeType(form[p.Name], p.PropertyType), null);
			}
			return obj;
		}
		public virtual ActionResult Save(FormCollection form)
		{
			if (!String.IsNullOrEmpty(form["Id"]) && form["Id"] != "0")
				return Update(form);
			return Insert(form);
		}

		BaseEntity<T> createInstance()
		{

			var ass = Assembly.GetAssembly(typeof(T));
			var obj = ass.CreateInstance(typeof(T).FullName) as BaseEntity<T>;
			return obj;
		}
    }
}
